package algocasts;

public class P92_DeleteNodeInBST {
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
    }

    public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) return null;
        if (key < root.val) {
            root.left = deleteNode(root.left, key);
        } else if (key > root.val) {
            root.right = deleteNode(root.right, key);
        } else {
            if (root.left == null) return root.right;
            else if (root.right == null) return root.left;
            TreeNode leftMax = root.left;
            while (leftMax.right != null) leftMax = leftMax.right;
            leftMax.right = root.right;
            root = root.left;
        }
        return root;
    }
}
